package com.ruoyi.service;

import com.ruoyi.common.core.domain.BusinessLogInfo;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.mapper.BusinessLogInfoMapper;
import com.ruoyi.common.core.mapper.SysDeptMapper;
import com.ruoyi.common.core.service.BaseServiceImpl;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * 业务日志
 * @date 2024-08-06
 */
@Service
public class BusinessLogInfoServiceImpl extends BaseServiceImpl<BusinessLogInfoMapper, BusinessLogInfo> {
    @Autowired
    private SysDeptMapper deptMapper;

    public void doSave(BusinessLogInfo businessLogInfo) {
        businessLogInfo.setCreateTime(DateUtils.getNowDate());
        businessLogInfo.insertOrUpdate();
    }

    public void deleteById(Long id) {
        baseMapper.deleteById(id);
    }

    /**
     * 保存业务日志
     */
    public void doSaveAudit(String business, String subBusiness, Long businessId, String log, String procInstId) {
        doSave(business, subBusiness, businessId, log, true, null, procInstId);
    }

    /**
     * 保存业务日志
     */
    public void doSave(String business, String subBusiness, Long businessId, String log, boolean isAudit, String files, String procInstId) {
        BusinessLogInfo businessLogInfo = new BusinessLogInfo();
        businessLogInfo.setBusiness(business);
        businessLogInfo.setSubBusiness(subBusiness);
        businessLogInfo.setProcInstId(procInstId);
        businessLogInfo.setBusinessId(businessId);
        if (SecurityUtils.getLoginUserCanNotLogin() != null) {
            SysUser user = SecurityUtils.getLoginUser().getUser();
            businessLogInfo.setUserName(user.getNickName());
            log = log.replace("{user}", user.getNickName());
            if (user.getDeptId() != null) {
                SysDept dept = deptMapper.selectById(user.getDeptId());
                log = log.replace("{dept}", dept.getDeptName());
            } else {
                log = log.replace("{dept}", "");
            }
        }
        businessLogInfo.setContent(log);
        businessLogInfo.setAudit(isAudit);
        businessLogInfo.setFiles(files);
        doSave(businessLogInfo);
    }

    /**
     * 保存业务日志
     */
    public void doSave(String business, String subBusiness, Long businessId, String log, boolean isAudit, String procInstId) {
        doSave(business, subBusiness, businessId, log, isAudit, null, procInstId);
    }

    /**
     * 保存业务日志
     */
    public void doSave(String business, String subBusiness, Long businessId, String log) {
        doSave(business, subBusiness, businessId, log, false, null);
    }

    public BusinessLogInfo findLastByProcInstId(String processInstanceId) {
        return baseMapper.findLastByProcInstId(processInstanceId);
    }
}
